<?php
class Bbling_PdfController extends Evebit_Controller_Action_Frontend {
	
	public function indexAction() {
		
	
	}
	
	public function createPdfAction() {
		//require_once ('../config/lang/eng.php');
		require_once 'config/lang/eng.php';
		require_once 'tcpdf.php';
		//require_once ('../tcpdf.php');
		
		$user = Zend_Auth::getInstance ()->getIdentity ();
		$id = $this->getRequest ()->getParam ( 'id' );
		
		// create new PDF document
		$pdf = new Evebit_Pdf_Tcpdf ( PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false , $user);
		
		// set document information
		$pdf->SetCreator ( PDF_CREATOR );
		$pdf->SetAuthor ( 'Nicola Asuni' );
		$pdf->SetTitle ( 'TCPDF Example 003' );
		$pdf->SetSubject ( 'TCPDF Tutorial' );
		$pdf->SetKeywords ( 'TCPDF, PDF, example, test, guide' );
		
		// set default header data
		$pdf->SetHeaderData ( PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING );
		
		// set header and footer fonts
		$pdf->setHeaderFont ( Array (PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN ) );
		$pdf->setFooterFont ( Array (PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA ) );
		
		// set default monospaced font
		$pdf->SetDefaultMonospacedFont ( PDF_FONT_MONOSPACED );
		
		//set margins
		$pdf->SetMargins ( PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT );
		$pdf->SetLeftMargin(24);
		$pdf->SetRightMargin(22);
		$pdf->SetHeaderMargin ( PDF_MARGIN_HEADER );
		$pdf->SetFooterMargin ( PDF_MARGIN_FOOTER );
		//set auto page breaks
		$pdf->SetAutoPageBreak ( TRUE, 50 );
		
		//set image scale factor
		$pdf->setImageScale ( PDF_IMAGE_SCALE_RATIO );
		
		//set some language-dependent strings
		$pdf->setLanguageArray ( $l );
		
		// ---------------------------------------------------------
		

		$items = $this->_getContent ( $id );

//		foreach ( $items as $key => $item ) {
//			// set font
//			$pdf->SetFont ( 'helvetica', 'B', 22 );
//			
//			// add a page
//			$pdf->AddPage (); // set some text to print
//			
//
//			// print a block of text using Write()
//			$big_title = ucwords ( str_replace ( '_', ' ', $key ) );
//			$pdf->Write ( $h = 20, $big_title, $link = '', $fill = 0, $align = 'L', $ln = true, $stretch = 0, $firstline = false, $firstblock = false, $maxh = 0 );
//			
//			foreach ( $item as $key2 => $item2 ) {
//				$unsetKeys = array ('id' );
//				if (in_array ( $key2, $unsetKeys )) {
//					continue;
//				}
//				$pdf->SetFont ( 'helvetica', 'B', 18 );
//				$pdf->Write ( $h = 18, ucwords ( str_replace ( '_', ' ', $key2 ) ), $link = '', $fill = 0, $align = 'L', $ln = true, $stretch = 0, $firstline = false, $firstblock = false, $maxh = 0 );
//				if ($item2) {
//					$pdf->SetFont ( 'helvetica', null, 12 );
//					$pdf->Write ( $h = 18, $item2, $link = '', $fill = 0, $align = 'L', $ln = true, $stretch = 0, $firstline = false, $firstblock = false, $maxh = 0 );
//				}
//			
//			}
//		
//		}

    if ( !empty( $items )){
		foreach ( $items as $key => $item){
		  // add a page
          $pdf->AddPage (); // set some text to print
          
		  $big_title = ucwords ( str_replace ( '_', ' ', $key ) );
		  
//		  $big_title_html = <<<EOF
//		  <div style="font-weight:bold;font-size:90px;text-align:left;">$big_title</div>
//EOF;
//          $pdf->writeHTML($big_title_html);
          $pdf->SetFont ( 'trebucb','',25);
          $pdf->Cell('',16,$big_title,'',1,'L',false,'',0,true,'','B');
          
          //write the second title
          foreach ( $item as $key2 => $item2){
            $unsetKeys = array('id','company_cv_files');
            if (in_array ( $key2, $unsetKeys )) {
				continue;
			}
			$second_title = ucwords ( str_replace ( '_', ' ', $key2 ) );
//			$second_title_html = <<<EOF
//            <br />
//			<div style="font-weight:bold;font-size:70px;text-align:left;">$second_title</div>
//EOF;
//            $pdf->writeHTML($second_title_html);
            
            
            $pdf->SetFont ( 'trebucb','B',18);
            $pdf->Cell('',16,$second_title,'',1,'L',false,'',0,true,'','B');
            $pdf->SetFont ( 'helvetica', '', 18 );
            
            //write the main contain
            if ($item2) {
				$third_title_html = <<<EOF
				<br />
				<div style="font-size:45px;text-align:left;font-family:Times New Roman;">$item2</div>
EOF;
           $pdf->writeHTML($third_title_html);
//              $pdf->SetFont ( 'pala','',10);
//              $pdf->Cell('',12,$item2,'',1,'L',false,'',0,true,'','B');
            	
			}//if
			
			
          }
		  
		}
    }
		
		
		//		
//		$TotalDatas = $this->_getTotalDatas($id);
//		print_r($TotalDatas);
//		echo '<br>';
//		$DetailDatas = $this->_getDetailDatas($id);
//		print_r($DetailDatas);
//		exit;
		//		
		//CREATE THE FINANCIAL PLAN MONTHLY SALES AND EXPENSES
		
		
		/*$pdf->SetFont ( 'trebucb','',18);
        $pdf->Cell('',16,'Sales Forecast','',1,'L',false,'',0,true,'','B');
        $pdf->SetFont ( 'trebucb','',14);
        $pdf->Cell('',12,'Sales Forecast Table','',1,'L',false,'',0,true,'','B');
        $pdf->Cell('',6,'','',1,'L',false,'',0,true,'','B');
		$financial_plan_table = $this->_create_financial_plan_table ();
		$pdf->writeHTML ( $financial_plan_table );
		
		$pdf->Cell('',6,'Sales by Month','',1,'L',false,'',0,true,'','B');
		$pdf->Cell('',4,'','',1,'L',false,'',0,true,'','B');
		$img_url = $this->_create_financial_monthly_chart_url();
    if( $img_url != ''){
		$fhandler_img_from = fopen($img_url, 'rb');
		$images_contents = stream_get_contents($fhandler_img_from);
		$pdf->Image('@'.$images_contents,70,'',100,60);
		$pdf->Cell('',55,'','',1,'L',false,'',0,true,'','B');
    }

        $pdf->SetFont ( 'trebucb','',18);
        $pdf->Cell('',16,'Budget','',1,'L',false,'',0,true,'','B');
        $pdf->SetFont ( 'trebucb','',14);
        $pdf->Cell('',12,'Budget Table','',1,'L',false,'',0,true,'','B');
        $pdf->Cell('',2,'','',1,'L',false,'',0,true,'','B');
		$financial_plan_budget_table = $this->_create_financial_budget_table();
		$pdf->writeHTML( $financial_plan_budget_table );
		
		$pdf->Cell('',6,'Expenses by Month','',1,'L',false,'',0,true,'','B');
		$pdf->Cell('',4,'','',1,'L',false,'',0,true,'','B');
		$img_url2 = $this->_create_financial_expenses_url();;
	if ( $img_url2 != ''){
		$fhandler_img_from2 = fopen($img_url2, 'rb');
		$images_contents2 = stream_get_contents($fhandler_img_from2);
        $pdf->Image('@'.$images_contents2,70,'',100,60);
        $pdf->Cell('',55,'','',1,'L',false,'',0,true,'','B');
	}
		
        $pdf->SetFont ( 'trebucb','',18);
        $pdf->Cell('',16,'Projected Profit and Loss Statement','',1,'L',false,'',0,true,'','B');
        $pdf->SetFont ( 'trebucb','',14);
        $pdf->Cell('',12,'Projected Profit and Loss Table','',1,'L',false,'',0,true,'','B');
        $pdf->Cell('',6,'','',1,'L',false,'',0,true,'','B');
		$financial_plan_profit_and_loss_table = $this->_create_financial_plan_profit_and_loss_table();
		$pdf->writeHTML($financial_plan_profit_and_loss_table);*/
		
		
		//$this->_create_financial_monthly_chart_url();
		
		
		//echo $financial_plan_profit_and_loss_table;
		//exit;
        //echo $financial_plan_budget_table;exit;
		
		//      $emailHelper = new Evebit_Email_Helper();
		//		$fullBasePath = $emailHelper->getFullBasePath();

//		
//		$img_url = 'http://chart.googleapis.com/chart?cht=p&chs=400x200&chtt=Sales%20per%20Month&chdl=January%7CFebruary%7CMarch&chdlp=r&chco=3399CC%2C00FF00%2C0000FF&chd=e%3A..qqP.&chp=0.628';
//        $fhandler_img_from = fopen($img_url, 'rb');
//		$images_contents = stream_get_contents($fhandler_img_from);
//        $pdf->Image('@'.$images_contents);
//        
//      $img_cache_dir = RP.DS.'media'.DS.'pdf_img_cache'.DS;
//		$img_tmp = $img_cache_dir . 'img_tmp_' . time() . '.png';
//		$fhandler_img_to = fopen($img_tmp, 'a');
//        
//		fclose($fhandler_img_to);
//		fwrite($fhandler_img_to, $images_contents);
//		//file_put_contents($img_tmp, $images_contents);
//        $pdf->Image($img_cache_dir . $img_tmp);
//        //unlink($img_tmp);
        
		
		
		
        
		// ---------------------------------------------------------
		

		//Close and output PDF document
		$pdf->Output ( 'example_003.pdf', 'I' );
		exit ();
		/*$user = Zend_Auth::getInstance ()->getIdentity ();
		$id = $this->getRequest ()->getParam ( 'id' );
		
		$pdf = new Zend_Pdf ();
		
		$datas = $this->_getContent ( $id );
		$pages = $this->_createPdfAction ( $datas );
		
		$businessEntity = new Bbling_Model_Entity_Business ();
		$financialId = $businessEntity->load ( $id )->financial_id;
		$balanace = new Bbling_Model_Entity_Balanace ();
		
		$items = $balanace->getBalanaceData ( $financialId );
		if (count ( $items )) {
			$tablePages = $this->_createPdfTableAction ( $items, array ('x' => 0, 'y' => 10 ) );
			
			$items = $balanace->getFinancialIdDatas ( array ('financial_id' => $financialId ) );
			$items = $this->arrayFilter ( $items, array ('id', 'financial_id', 'sales', 'cost_off' ) );
			$tablePages = $this->_createPdfTableAction ( $items, array ('x' => 0, 'y' => 350 ), $tablePages [0] );
			$pages = array_merge ( $pages, $tablePages );
		}
		
		foreach ( $pages as $page ) {
			$pdf->pages [] = $page;
		}
		
		header ( "Content-Disposition: inline; filename=result.pdf" );
		header ( "Content-type: application/x-pdf" );
		echo $pdf->render ();
		exit ();*/
	}
	
	protected function _getTotalDatas($id) {
		$businessEntity = new Bbling_Model_Entity_Business ();
		$financialId = $businessEntity->load ( $id )->financial_id;
		$balanace = new Bbling_Model_Entity_Balanace ();
		
		$items = $balanace->getBalanaceData ( $financialId );
		
		return $items;
	}
	
	protected function _getDetailDatas($id) {
		$businessEntity = new Bbling_Model_Entity_Business ();
		$financialId = $businessEntity->load ( $id )->financial_id;
		$balanace = new Bbling_Model_Entity_Balanace ();
		
		$datas = $balanace->getFinancialIdDatas ( array ('financial_id' => $financialId ) );
	    if( empty( $datas ) ){ 
		  return;
	    }
	    $datas = Evebit_Array_Helper::arrayFilter ( $datas, array ('id', 'financial_id', 'sales', 'cost_off' ) );
		return $datas;
	}
	
    protected function _getContent($id) {
		$businessEntity = new Bbling_Model_Entity_Business ();
		$businessEntity->load ( $id );
		$extraData = $businessEntity->extraLoad ();
		
		$extraData2 ['executive_summary'] ['company_summary'] = $extraData ['company'] ['company_summary'];
		$extraData2 ['executive_summary'] ['financial_summary'] = $extraData ['financial'] ['financial_summary'];
		$extraData2 ['executive_summary'] ['product_summary'] = $extraData ['product'] ['product_summary'];
		$extraData2 ['executive_summary'] ['marketing_summary'] = $extraData ['marketing'] ['marketing_summary'];
		
		$extraData2['company']['company_overview'] = $extraData['company']['company_overview'];
		$extraData2['company']['management_team'] = $extraData['company']['management_team'];
		
		$extraData2['products_and_services']['competitors'] = $extraData['product']['competitors'];
		$extraData2['products_and_services']['product_overview'] = $extraData['product']['product_overview'];
		$extraData2['products_and_services']['your_edge'] = $extraData['product']['your_edge'];
		
		$extraData2['target_market']['market_overview'] = $extraData['marketing']['market_overview'];
		$extraData2['target_market']['market_needs'] = $extraData['marketing']['market_needs'];
		
		$extraData2['marketing_plan']['marketing_overview'] = $extraData['marketing']['marketing_overview'];
		$extraData2['marketing_plan']['positioning'] = $extraData['marketing']['positioning'];
		$extraData2['marketing_plan']['pricing'] = $extraData['marketing']['pricing'];
		
		$extraData2['financial_plan']['sales_forecast'] = '';
		$extraData2['financial_plan']['sales_forecast_table'] = '';
		$extraData2['financial_plan']['sales_by_month'] = '';
		$extraData2['financial_plan']['budget'] = '';
		$extraData2['financial_plan']['budget_table'] = '';
		$extraData2['financial_plan']['expenses_by_month'] = '';
		$extraData2['financial_plan']['projected_profit_and_loss_statement'] = '';
		$extraData2['financial_plan']['projected_profit_and_loss_table'] = '';
		
		//$extraData = array_merge ( $extraData2, $extraData );
		//$extraData = Evebit_Array_Helper::arrayFilter ( $extraData, array ('company_cv_files' ) );
		return $extraData2;
	}
	
	protected function _createPdfAction($datas = null) {
		if ($datas == null || ! is_array ( $datas )) {
			return false;
		}
		
		$page = new Evebit_Pdf_Page ( Zend_Pdf_Page::SIZE_A4 );
		foreach ( $datas as $item ) {
			$option = array_key_exists ( 'option', $item ) ? $item ['option'] : null;
			$page->setFont ( $item ['font'] [0], $item ['font'] [1] );
			$lines = $page->wrapText ( $item ['content'] );
			$result = $page->checkHeight ( $lines, $option );
			if ($result ['current']) {
				$page->drawTextBlock ( $result ['current'], $option );
			}
			if ($result ['next']) {
				$pages [] = $page;
				$page = new Evebit_Pdf_Page ( Zend_Pdf_Page::SIZE_A4 );
				$page->setFont ( $item ['font'] [0], $item ['font'] [1] );
				$page->drawTextBlock ( $result ['next'], $option );
			}
		}
		$pages [] = $page;
		
		return $pages;
	}
	
	protected function _createPdfTableAction($datas = null, $options = null, Zend_Pdf_Page $page = null) {
		$posX = array_key_exists ( 'x', $options ) ? $options ['x'] : 0;
		$posY = array_key_exists ( 'y', $options ) ? $options ['y'] : 0;
		
		$style_body = new Zend_Pdf_Style ();
		$style_body->setLineWidth ( 1 );
		
		if (! $page) {
			$page = new My_Pdf_Page ( My_Pdf_Page::SIZE_A4 );
			$page->setMargins ( array ('10', '20', '10', '20' ) );
		}
		$table = new My_Pdf_Table ( 2 );
		
		$cols = array ();
		for($i = 0; $i < count ( $datas ); $i ++) {
			if ($i === 0) {
				$headers = array_keys ( $datas [0] );
				foreach ( $headers as $header ) {
					$col = new My_Pdf_Table_Column ();
					$col->setText ( ucwords ( str_replace ( '_', ' ', $header ) ) );
					$cols [] = $col;
				}
				$row = new My_Pdf_Table_HeaderRow ();
				$row->setAlignment ( My_Pdf::LEFT );
				$row->setFont ( Zend_Pdf_Font::fontWithName ( Zend_Pdf_Font::FONT_HELVETICA ), 6 );
				$row->setColumns ( $cols );
				$table->setHeader ( $row );
			}
			
			$cols = array ();
			$row = new My_Pdf_Table_Row ();
			$row->setBorder ( My_Pdf::BOTTOM, $style_body );
			$row->setCellPadding ( My_Pdf::BOTTOM, 15 );
			$row->setCellPadding ( My_Pdf::TOP, 2 );
			foreach ( $datas [$i] as $value ) {
				$col = new My_Pdf_Table_Column ();
				$col->setText ( $value );
				$cols [] = $col;
			}
			$row->setColumns ( $cols );
			$table->addRow ( $row );
		}
		
		$page->addTable ( $table, $posX, $posY );
		$pages = $page->getPages ();
		if ($pages) {
			foreach ( $pages as $item ) {
				$pages [] = $item;
			}
		} else {
			$pages [] = $page;
		}
		
		return $pages;
	}
	
	/**
	 * REGURN THE MONTHLY SALES AND EXPENSES TABLE HTML
	 * @author Ma.XiaoHui
	 */
	protected function _create_financial_plan_table() {
		$id = $this->getRequest ()->getParam ( 'id' );
		$TotalDatas = $this->_getTotalDatas ( $id );
		//	    THE FINANCIAL TABLE LIKE THIS
		//		$financial_plan_table = <<<EOF
		//		<h2>Sales Forecast</h5>
		//		<div style="text-align:left;font-weight:bold;">Sales Forecast Table</div>
		//		<table>
		//		  <thead>
		//		    <tr>
		//		      <td style="border-bottom:1px solid #231F20;"></td>
		//		      <td style="border-bottom:1px solid #231F20;">Jan</td>
		//		      <td style="border-bottom:1px solid #231F20;">Feb</td>
		//		    </tr>
		//		  </thead>
		//		  <tr>
		//		    <td style="border-bottom:1px solid #231F20;">Sales</td>
		//		    <td style="border-bottom:1px solid #231F20;">100</td>
		//		    <td style="border-bottom:1px solid #231F20;">200</td>
		//		  </tr>
		//		  <tr>
		//		    <td>Expenses</td>
		//		    <td>50</td>
		//		    <td>20</td>
		//		  </tr>
		//		</table>
		//		
		//EOF;
		
		
        		$financial_plan_table = <<<EOF
		<br />
		<table style="border-spacing:0px;font-size:30px;">
		  <thead>
		    <tr>
		      <td style="border-bottom:1px solid #231F20;width:100px;"></td>
EOF;
//		$financial_plan_table = <<<EOF
//		<br />
//        <h2>Sales Forecast</h2>
//		<div style="text-align:left;font-weight:bold;">Sales Forecast Table</div>
//		<br />
//		<table style="border-spacing:0px;font-size:30px;">
//		  <thead>
//		    <tr>
//		      <td style="border-bottom:1px solid #231F20;width:100px;"></td>
//EOF;
      if( !empty( $TotalDatas )){
		foreach ( $TotalDatas as $key => $value ) {
			$financial_plan_table .= '<td style="border-bottom:1px solid #231F20;width:45px;">' . $value ['month'] . '</td>';
		}
		
		$financial_plan_table .= '</tr>
        	                    </thead>
        	                      <tr>
        	                        <td style="border-bottom:1px solid #231F20;width:100px;">Sales</td>';
		foreach ( $TotalDatas as $key => $value ) {
			$financial_plan_table .= '<td style="border-bottom:1px solid #231F20;width:45px;">' . $value ['sales'] . '</td>';
		}
		
		$financial_plan_table .= '</tr>
		                          <tr >
		                            <td style="border-bottom:1px solid #231F20;width:100px;">Expenses</td>';
		foreach ( $TotalDatas as $key => $value ) {
			$financial_plan_table .= '<td style="border-bottom:1px solid #231F20;width:45px;">' . $value ['expenses'] . '</td>';
		}
		
		$financial_plan_table .= '</tr>
		                        </table>
		                        ';
      } else {
        $financial_plan_table = '';
      }
		return $financial_plan_table;
	
	}
	
	protected function _create_financial_budget_table()
	{
	    $id = $this->getRequest ()->getParam ( 'id' );
		$DetailDatas = $this->_getDetailDatas($id);
//		$financial_budget_table = <<<EOF
//		<h1>Budget</h1>
//		<h3>Budget Table</h3>
//		<table style="border-spacing:0px;">
//		  <thead>
//		    <tr>
//		      <td style="border-bottom:0.4px solid;">&nbsp;</td>
//		      <td style="border-bottom:0.4px solid;">Jan</td>
//		      <td style="border-bottom:0.4px solid;">Feb</td>
//		    </tr>
//		  </thead>
//		  <tr>
//		    <td cols="3" style="height:35px;font-size:35px;font-weight:bold;">
//		      <div>Expenses</div>
//		    </td>
//		  </tr>
//		  <tr>
//		    <td style="height:20px;text-indent:15px;font-size:30px;">Salary</td>
//		    <td style="height:20px;font-size:30px;">10</td>
//		    <td style="height:20px;font-size:30px;">20</td>
//		  </tr>
//		  <tr>
//		    <td style="height:30px;font-size:35px;font-weight:bold;border-bottom:0.4px solid;">Total Expenses</td>
//		    <td style="height:30px;font-size:35px;font-weight:bold;border-bottom:0.4px solid;">10</td>
//		    <td style="height:30px;font-size:35px;font-weight:bold;border-bottom:0.4px solid;">20</td>
//		  </tr>
//		  
//		</table>
//EOF;
        $months = array(
          1 => 'Jan',
          2 => 'Feb',
          3 => 'Mar',
          4 => 'Apr',
          5 => 'May',
          6 => 'Jun',
          7 => 'Jul',
          8 => 'Aug',
          9 => 'Sep',
          10 => 'Oct',
          11 => 'Nov',
          12 => 'Dec'
        );
        $financial_budget_table = <<<EOF
        <table style="border-spacing:0px;">
          <thead>
            <tr>   
              <td style="width:100px;">&nbsp;</td>     
EOF;
//        $financial_budget_table = <<<EOF
//        <table><tr><td style="height:200px;">&nbsp;</td></tr></table>
//        <h1>Budget</h1>
//        <h3>Budget Table</h3>
//        <table style="border-spacing:0px;">
//          <thead>
//            <tr>   
//              <td style="width:100px;">&nbsp;</td>     
//EOF;
      if( !empty( $DetailDatas )){
        foreach ($DetailDatas as $value) {
        	  $financial_budget_table .='
        	                             <td style="width:45px;font-size:30px;text-align:left;">'. $months[ $value['month'] ] .'</td>
        	                             ';
        }
        $financial_budget_table .= '
            </tr>
		  </thead>
		  <tr>
		    <td><hr width="100"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="100"/></td>
		    <td><hr width="100"/></td>
		  </tr>
		  <tr>
		    <td style="font-size:35px;width:100px;font-weight:bold;text-align:left;">
		      Expenses
		    </td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		  </tr>';
        
        //fetch the expenses items
        $key_arr = array();
        foreach ( $DetailDatas[0] as $key2 => $value2){
          if ( $key2!='month') {
          	$key_arr[] = $key2; 
          }
        }
        

        foreach ($key_arr as $key3 => $value3){
          $financial_budget_table .='
                <tr>
                  <td style="height:20px;font-size:30px;width:100px;aiign:left;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'. $value3 .'</td>';
          foreach ( $DetailDatas as $key4 => $value4){
            $financial_budget_table .= '
               <td style="height:20px;font-size:30px;text-align:left;">'. $value4[$value3] .'</td> 
            ';
          }

          $financial_budget_table .= '</tr>';
        }
		
        $financial_budget_table .='
		  <tr>
		    <td style="font-size:35px;width:100px;font-weight:bold;text-align:left;">Total Expenses</td>';
        
        //fetch the total expenses
        $total = array();
		foreach ( $DetailDatas as $key5 => $value5 ){
		    $total [ $months[ $value5['month'] ] ] = 0;
		    foreach ($value5 as $key6 => $value6 ){
		    	if( $key6 != 'month'){
		          $total [ $months[ $value5['month'] ] ] += $value6;
		    	}
		    }  
		}
		
		foreach ( $total as $key7 => $value7 ){
		    $financial_budget_table .='
		      <td style="width:45px;font-size:30px;text-align:left;">'. $value7 .'</td>';
		}
        
		
        $financial_budget_table .= '
          </tr>
          <tr>
		    <td><hr width="100"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		    <td><hr width="50"/></td>
		  </tr>
        </table>
        ';
      }else {
          $financial_budget_table = '';
      }
        return $financial_budget_table;
	}
	
	protected function _create_financial_plan_profit_and_loss_table()
	{
		$id = $this->getRequest ()->getParam ( 'id' );
		$DetailDatas = $this->_getDetailDatas($id);
	    $TotalDatas = $this->_getTotalDatas ( $id );
	    $months = array(
          1 => 'Jan',
          2 => 'Feb',
          3 => 'Mar',
          4 => 'Apr',
          5 => 'May',
          6 => 'Jun',
          7 => 'Jul',
          8 => 'Aug',
          9 => 'Sep',
          10 => 'Oct',
          11 => 'Nov',
          12 => 'Dec'
        );
	    

	   $financial_plan_profit_and_loss_table = <<<EOF
		<table style="border-spacing:0px;font-size:30px;">
		  <thead>
		    <tr>
		      <td style="border-bottom:1px solid #231F20;width:100px;"></td>
EOF;
      if ( !empty( $TotalDatas )){
		foreach ( $TotalDatas as $key => $value ) {
			$financial_plan_profit_and_loss_table .= '<td style="border-bottom:1px solid #231F20;width:45px;">' . $value ['month'] . '</td>';
		}
		
		$financial_plan_profit_and_loss_table .= '</tr>
        	                    </thead>
        	                      <tr>
        	                        <td style="border-bottom:1px solid #231F20;width:100px;font-weight:bold;">&nbsp;&nbsp;Sales</td>';
		foreach ( $TotalDatas as $key => $value ) {
			$financial_plan_profit_and_loss_table .= '<td style="border-bottom:1px solid #231F20;width:45px;">' . $value ['sales'] . '</td>';
		}
		
		
		$financial_plan_profit_and_loss_table .='
		  </tr>
		  <tr>
		    <td style="font-size:35px;width:100px;font-weight:bold;text-align:left;">
		      Expenses
		    </td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		    <td style="width:45px;font-size:35px;text-align:center;">&nbsp;</td>
		  </tr>
		';
		
	    //fetch the expenses items
        $key_arr = array();
        foreach ( $DetailDatas[0] as $key2 => $value2){
          if ( $key2!='month') {
          	$key_arr[] = $key2; 
          }
        }
        

        foreach ($key_arr as $key3 => $value3){
          $financial_plan_profit_and_loss_table .='
                <tr>
                  <td style="height:20px;font-size:30px;width:100px;aiign:left;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'. $value3 .'</td>';
          foreach ( $DetailDatas as $key4 => $value4){
            $financial_plan_profit_and_loss_table .= '
               <td style="height:20px;font-size:30px;text-align:left;">'. $value4[$value3] .'</td> 
            ';
          }

          $financial_plan_profit_and_loss_table .= '</tr>';
        }
		
	    $financial_plan_profit_and_loss_table .='
		  <tr>
		    <td style="font-size:35px;width:100px;font-weight:bold;text-align:left;">Total Expenses</td>';
        
        //fetch the total expenses
        $total = array();
		foreach ( $DetailDatas as $key5 => $value5 ){
		    $total [ $months[ $value5['month'] ] ] = 0;
		    foreach ($value5 as $key6 => $value6 ){
		    	if( $key6 != 'month'){
		          $total [ $months[ $value5['month'] ] ] += $value6;
		    	}
		    }  
		}
		
		foreach ( $total as $key7 => $value7 ){
		    $financial_plan_profit_and_loss_table .='
		      <td style="width:45px;font-size:30px;text-align:left;">'. $value7 .'</td>';
		}
        
		//caculate the profit
		$net_profit = array();
		$net_profit_div_sales = array();
		foreach ($TotalDatas as $key => $value) {
			$net_profit[] = $value['sales'] - $value['expenses'];
			if ( $value['sales']  == 0 || $value['sales'] == null ){
			  $net_profit_div_sales[] =  sprintf("--");
			} else {
			  $net_profit_div_sales[] =  sprintf("%.0f%%",( ($value['sales'] - $value['expenses'])/$value['sales'] )*100 );
			}
			
		}

		$financial_plan_profit_and_loss_table .='
		  </tr>
		  <tr>
		    <td style="font-size:35px;width:100px;font-weight:bold;text-align:left;">Net Profit</td>';
		foreach ($net_profit as $value) {
			$financial_plan_profit_and_loss_table .='
		      <td style="width:45px;font-size:30px;text-align:left;">'. $value .'</td>';
		}
		
	    $financial_plan_profit_and_loss_table .='
		  </tr>
		  <tr>
		    <td style="font-size:35px;width:100px;font-weight:bold;text-align:left;">Net Profit/Sales</td>';
		foreach ($net_profit_div_sales as $value) {
			$financial_plan_profit_and_loss_table .='
		      <td style="width:45px;font-size:30px;text-align:left;">'. $value .'</td>';
		}
		
		
		$financial_plan_profit_and_loss_table .= '
		  </tr>
		  <tr>
		    <td><hr width="100"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		    <td><hr width="45"/></td>
		  </tr>
		</table>';
      }else {
          $financial_plan_profit_and_loss_table = '';
      }
		return $financial_plan_profit_and_loss_table;
		
        
     }
     
     protected function _create_financial_monthly_chart_url()
     {
         $id = $this->getRequest ()->getParam ( 'id' );
		 //$DetailDatas = $this->_getDetailDatas($id);
	     $TotalDatas = $this->_getTotalDatas ( $id );
	     
	     $googleChart_baseUrl = 'http://chart.googleapis.com/chart?cht=bvg&chs=500x400&chco=4EA1D9,C6D9FD&chbh=15,4,15&chds=a&chxt=x,y,x&chg=0,20&'; 
	     //http://chart.googleapis.com/chart?cht=bvg&chs=400x400&chco=4D89F9,C6D9FD&chbh=15,4,15&chds=a&chxt=x,y&chg=0,20&chd=t:5,30,50,80,200,300,400&chxl=0:|Jan|Feb|Mar|Apr|May|Jun|July
	     $data = 'chd=t:';
	     $label = 'chxl=0:|';
	     $data_arr = array();
	     $label_arr = array();
	  if (!empty( $TotalDatas )){   
	     foreach ( $TotalDatas as $key => $value){
	       $data_arr[] = $value['sales'];
	       $label_arr[] = $value['month']; 
	     }
	     
	     $data .= implode(',', $data_arr);
	     $label .= implode('|', $label_arr);
	     $label .= '|2:|Months&chxp=2,50';
	     return $googleChart_baseUrl . $data . '&' . $label;
	  }else return '';
     
     }
     
     protected function _create_financial_expenses_url()
     {
         $id = $this->getRequest ()->getParam ( 'id' );
		 $DetailDatas = $this->_getDetailDatas($id);
		 
		 $months = array(
          1 => 'Jan',
          2 => 'Feb',
          3 => 'Mar',
          4 => 'Apr',
          5 => 'May',
          6 => 'Jun',
          7 => 'Jul',
          8 => 'Aug',
          9 => 'Sep',
          10 => 'Oct',
          11 => 'Nov',
          12 => 'Dec'
        );
        
        $months_arr = array();
        $total = array();
      if (!empty( $DetailDatas )){
        foreach ($DetailDatas as $value) {
        	$months_arr[] = $months[ $value['month'] ];
        	$total[ $months[ $value['month'] ] ] = 0;
        	foreach ( $value as $key2 => $value2 ){
        		if( $key2 != 'month'){
        	        $total[ $months[ $value['month'] ] ] += $value2;
        		}
        	}
        }

        $googleChart_baseUrl = 'http://chart.googleapis.com/chart?cht=bvg&chs=500x400&chco=4EA1D9,C6D9FD&chbh=15,4,15&chds=a&chxt=x,y,x&chg=0,20&'; 
	    //https://chart.googleapis.com/chart?cht=bvg&chs=400x400&chco=4D89F9,C6D9FD&chbh=15,4,15&chds=a&chxt=x,y&chg=0,20&chd=t:5,30,50,80,200,300,400&chxl=0:|Jan|Feb|Mar|Apr|May|Jun|July
	    $data = 'chd=t:';
	    $label = 'chxl=0:|';
	    $data .= implode(',', $total);
	    $label .= implode('|', $months_arr);
	    $label .= '|2:|Months&chxp=2,50';
	    return $googleChart_baseUrl . $data . '&' . $label;
      } else return '';
		 
     }

}